/*
 * Let pi (for 0<=i<=255) be the frequency of byte i in plaintext
 * - i.e., pi = 0 for i<32 or i>127
 * - i.e., p97 = frequency of 'a'
 *
 * If the key length is N, then every Nth character of th plaintext is
 * is encrypted using the same shift
 * 
 * - If we take every Nth character and calculate frequencies we should 
 * get the pis in permuted order
 * 
 * - if we take every Mth character (M not multiple of N) and calculate
 * the frequencies, we should get something close to uniform
 *
 *
 *
 */
package pt.mleiria.cipher;

import java.util.logging.Logger;

/**
 *
 * @author manuel
 */
public class VigenerCipher extends Cipher {

    private final static Logger LOGGER = Logger.getLogger(VigenerCipher.class.getName());
    
    public VigenerCipher(final String key) {
        symKey = new VigenerKey(key);
    }
    
    
    public void encrypt() {
        /*
        final byte[] plainText = MathUtils.StringToBytesASCII(s);
        final byte[] k = MathUtils.StringToBytesASCII(key);
        */
        //final byte[] plainText = s.getBytes();
        final byte[] b = xorWithKey(getPlainText());
        setCipherText(b);
    }

    public void decrypt() {
        /*
        final byte[] cipherText = MathUtils.StringToBytesASCII(s);
        final byte[] k = MathUtils.StringToBytesASCII(key);
        */
        //final byte[] cipherText = s.getBytes();
        final byte[] b = xorWithKey(getCipherText());
        setPlainText(b);
    }

    /**
     *
     * @param a
     * @param key
     * @return
     */
    private byte[] xorWithKey(byte[] a) {
        byte[] out = new byte[a.length];
        for (int i = 0; i < a.length; i++) {
            out[i] = (byte) (a[i] ^ symKey.getKey()[i % symKey.getKey().length]);
        }
        return out;
    }

}
